package cn.e2win.biz.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import cn.e2win.base.entity.SysUser;

public class CloneUtils  {
		private static final long serialVersionUID = 1L;


		public static Map clone(Map map) {
			Map<Object, Object> target = new HashMap<Object, Object>();
			try {
				ByteArrayOutputStream byteout = null;
				ObjectOutputStream out = null;
				Object obj = null;
				if(map!=null){
					for (Iterator<Object> keyIt = map.keySet().iterator(); keyIt
							.hasNext();) {
						Object key = keyIt.next();
						byteout = new ByteArrayOutputStream();
						out = new ObjectOutputStream(byteout);
						out.writeObject(map.get(key));
						ByteArrayInputStream bytein = new ByteArrayInputStream(
								byteout.toByteArray());
						ObjectInputStream in = new ObjectInputStream(bytein);
						obj = in.readObject();// 反序列化出来，就相当于将原来的值和地址（即引用）copy了一份
						target.put(key, obj);// 习惯上一般key是不做修改的，因此没有copy key的必要
						// ，倘若有必要则同样反序列化出来就行了（如果是String类型也无需反序列化，上面已经解释的很清楚了）
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return target;
		}
	

	public static void main(String[] args) {
		SysUser user1 = new SysUser();
		user1.setId(1111111111);
		user1.setUserName("abc");
		user1.setCreateDate(new Timestamp(System.currentTimeMillis()));
		Map source = new HashMap();
		source.put("user1", user1);
		source.put("date1", "2000-01-01");

		System.out.println("source======     "+source);// 源，没有被修改
		Map target = CloneUtils.clone(source);
		SysUser user = (SysUser) target.get("user1");
		user.setId(222);// 改变副本的值
		user.setUserName("def");
		user.setCreateDate(new Timestamp(System.currentTimeMillis()));
		target.put("date1", new Date());
		
		System.out.println("target======     "+target);// 对比结果
		System.out.println("===========");
		
		System.out.println("source======     "+source);// 源，没有被修改
	}
}
